// pages/thief/select/index.js
Page({
  data: {
    // 用户数据
    userInfo: {},
    partnerInfo: {},
    stealChances: 3,
    maxChances: 3,
    lastStealTime: null,
    
    // 角色库数据
    characters: [
      {
        id: 'cute_cat',
        name: '萌萌小猫',
        avatar: '🐱',
        description: '软萌可爱的小猫咪，最擅长偷走你的烦恼',
        specialty: '治愈系',
        unlocked: true,
        level: 5,
        experience: 1250,
        maxExperience: 2000,
        skills: ['安慰', '撒娇', '卖萌'],
        successRate: 85,
        lastActive: '2小时前'
      },
      {
        id: 'wise_owl',
        name: '智慧猫头鹰',
        avatar: '🦉',
        description: '博学的猫头鹰，能够偷走你的焦虑和困惑',
        specialty: '智慧系',
        unlocked: true,
        level: 3,
        experience: 680,
        maxExperience: 1000,
        skills: ['分析', '建议', '冥想'],
        successRate: 78,
        lastActive: '1天前'
      },
      {
        id: 'happy_dog',
        name: '快乐小狗',
        avatar: '🐶',
        description: '活泼的小狗狗，专门偷走负面情绪',
        specialty: '活力系',
        unlocked: false,
        level: 1,
        experience: 0,
        maxExperience: 500,
        skills: ['陪伴', '游戏', '鼓励'],
        successRate: 72,
        unlockCondition: '完成10次偷取任务'
      },
      {
        id: 'gentle_rabbit',
        name: '温柔兔兔',
        avatar: '🐰',
        description: '温柔的小兔子，轻柔地带走你的伤心',
        specialty: '温柔系',
        unlocked: false,
        level: 1,
        experience: 0,
        maxExperience: 500,
        skills: ['倾听', '拥抱', '安抚'],
        successRate: 80,
        unlockCondition: '达到亲密度50'
      },
      {
        id: 'magic_fox',
        name: '神秘狐狸',
        avatar: '🦊',
        description: '神秘的九尾狐，拥有强大的心情转换能力',
        specialty: '神秘系',
        unlocked: false,
        level: 1,
        experience: 0,
        maxExperience: 1500,
        skills: ['变换', '魅惑', '治愈'],
        successRate: 95,
        unlockCondition: '收集100个心情碎片'
      }
    ],
    
    // 当前选中的角色
    selectedCharacter: null,
    
    // 偷取状态
    stealingStatus: {
      isActive: false,
      progress: 0,
      targetMood: '',
      timeRemaining: 0
    },
    
    // 今日统计
    todayStats: {
      totalSteals: 12,
      successfulSteals: 10,
      moodFragments: 25,
      experienceGained: 180
    },
    
    // 动画状态
    animations: {},
    showCharacterDetail: false,
    detailCharacter: null
  },

  onLoad(options) {
    // 检查用户是否已登录
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    const user = wx.getStorageSync('user');
    
    // 检查多种可能的登录状态存储方式
    if (!token || (!userInfo && !user)) {
      // 用户未登录，跳转到登录页面
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.initAnimations();
    this.loadCharacterData();
    this.checkActiveSteal();
    this.loadUserData();
  },

  onShow() {
    // 检查用户是否已登录
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    const user = wx.getStorageSync('user');
    
    // 检查多种可能的登录状态存储方式
    if (!token || (!userInfo && !user)) {
      // 用户未登录，跳转到登录页面
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.refreshData();
    this.loadUserData();
  },

  // 初始化动画
  initAnimations() {
    const animations = {};
    
    // 角色卡片动画
    animations.cardFloat = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease-in-out'
    });
    
    // 选择动画
    animations.selectPulse = wx.createAnimation({
      duration: 600,
      timingFunction: 'ease-in-out'
    });
    
    this.setData({ animations });
    
    // 启动浮动动画
    this.startFloatAnimation();
  },

  // 启动浮动动画
  startFloatAnimation() {
    const animation = this.data.animations.cardFloat;
    
    const float = () => {
      animation.translateY(-10).step({ duration: 2000 });
      animation.translateY(0).step({ duration: 2000 });
      
      this.setData({
        'animations.cardFloat': animation.export()
      });
      
      setTimeout(float, 4000);
    };
    
    float();
  },

  // 加载角色数据
  loadCharacterData() {
    // 从本地存储或服务器加载角色数据
    try {
      const savedData = wx.getStorageSync('thief_characters');
      if (savedData) {
        this.setData({
          characters: savedData
        });
      }
    } catch (err) {
      console.error('加载角色数据失败', err);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  },

  // 检查是否有正在进行的偷取任务
  checkActiveSteal() {
    try {
      const activeSteal = wx.getStorageSync('active_steal');
      if (activeSteal && activeSteal.endTime > Date.now()) {
        this.setData({
          stealingStatus: {
            isActive: true,
            progress: this.calculateProgress(activeSteal),
            targetMood: activeSteal.targetMood,
            timeRemaining: activeSteal.endTime - Date.now()
          }
        });
        
        this.startStealCountdown();
      }
    } catch (err) {
      console.error('检查活动偷取任务失败', err);
    }
  },

  // 计算偷取进度
  calculateProgress(stealData) {
    const totalTime = stealData.duration;
    const elapsed = Date.now() - stealData.startTime;
    return Math.min(100, (elapsed / totalTime) * 100);
  },

  // 开始偷取倒计时
  startStealCountdown() {
    const updateCountdown = () => {
      const status = this.data.stealingStatus;
      if (!status.isActive) return;
      
      const remaining = status.timeRemaining - 1000;
      if (remaining <= 0) {
        this.completeSteal();
        return;
      }
      
      // 格式化时间显示为 mm:ss
      const minutes = Math.floor(remaining / 60000);
      const seconds = Math.floor((remaining % 60000) / 1000);
      
      this.setData({
        'stealingStatus.timeRemaining': remaining,
        'stealingStatus.progress': Math.min(100, 100 - (remaining / (30 * 60 * 1000)) * 100),
        'stealingStatus.timeDisplay': `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
      });
      
      setTimeout(updateCountdown, 1000);
    };
    
    // 初始化时间显示
    const minutes = Math.floor(this.data.stealingStatus.timeRemaining / 60000);
    const seconds = Math.floor((this.data.stealingStatus.timeRemaining % 60000) / 1000);
    this.setData({
      'stealingStatus.timeDisplay': `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    });
    
    updateCountdown();
  },

  // 完成偷取
  completeSteal() {
    const character = this.data.selectedCharacter;
    const success = Math.random() < (character.successRate / 100);
    
    this.setData({
      'stealingStatus.isActive': false,
      'stealingStatus.progress': 100
    });
    
    // 显示结果
    this.showStealResult(success);
    
    // 更新角色经验
    if (success) {
      this.updateCharacterExperience(character.id, 50);
    }
    
    // 清除本地存储
    wx.removeStorageSync('active_steal');
  },

  // 显示偷取结果
  showStealResult(success) {
    const title = success ? '偷取成功！' : '偷取失败';
    const content = success 
      ? `${this.data.selectedCharacter.name}成功偷走了你的${this.data.stealingStatus.targetMood}！`
      : '这次没有成功，不过没关系，下次一定可以的！';
    
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      confirmText: '知道了',
      success: (res) => {
        if (success) {
          this.celebrateSuccess();
        }
      }
    });
  },

  // 庆祝成功动画
  celebrateSuccess() {
    // 播放成功动画和音效
    wx.showToast({
      title: '心情变好了！',
      icon: 'success',
      duration: 2000
    });
  },

  // 选择角色
  onSelectCharacter(e) {
    const characterId = e.currentTarget.dataset.id;
    const character = this.data.characters.find(c => c.id === characterId);
    
    if (!character.unlocked) {
      wx.showToast({
        title: `需要${character.unlockCondition}`,
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    this.setData({ selectedCharacter: character });
    
    // 播放选择动画
    const animation = this.data.animations.selectPulse;
    animation.scale(1.1).step({ duration: 300 });
    animation.scale(1).step({ duration: 300 });
    
    this.setData({
      'animations.selectPulse': animation.export()
    });
  },

  // 查看角色详情
  onViewCharacterDetail(e) {
    const characterId = e.currentTarget.dataset.id;
    const character = this.data.characters.find(c => c.id === characterId);
    
    this.setData({
      detailCharacter: character,
      showCharacterDetail: true
    });
  },

  // 关闭角色详情
  onCloseCharacterDetail() {
    this.setData({
      showCharacterDetail: false,
      detailCharacter: null
    });
  },

  // 开始偷取心情
  onStartSteal() {
    if (!this.data.selectedCharacter) {
      wx.showToast({
        title: '请先选择角色',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.stealingStatus.isActive) {
      wx.showToast({
        title: '已有偷取任务进行中',
        icon: 'none'
      });
      return;
    }
    
    // 检查偷取次数
    if (this.data.stealChances <= 0) {
      wx.showToast({
        title: '今日次数已用完',
        icon: 'none'
      });
      
      // 提供查看结果的选项
      wx.showModal({
        title: '提示',
        content: '今日偷取次数已用完，是否查看已完成的心情偷取？',
        success: (res) => {
          if (res.confirm) {
            this.viewResults();
          }
        }
      });
      return;
    }
    
    // 选择要偷取的心情
    wx.showActionSheet({
      itemList: ['😢 伤心', '😰 焦虑', '😡 愤怒', '😔 沮丧', '😫 疲惫'],
      success: (res) => {
        const moods = ['伤心', '焦虑', '愤怒', '沮丧', '疲惫'];
        const selectedMood = moods[res.tapIndex];
        this.startStealProcess(selectedMood);
      }
    });
  },

  // 开始偷取流程
  startStealProcess(mood) {
    const duration = 30 * 60 * 1000; // 30分钟
    const startTime = Date.now();
    const endTime = startTime + duration;
    
    const stealData = {
      characterId: this.data.selectedCharacter.id,
      targetMood: mood,
      startTime,
      endTime,
      duration
    };
    
    // 保存到本地存储
    wx.setStorageSync('active_steal', stealData);
    
    this.setData({
      'stealingStatus.isActive': true,
      'stealingStatus.progress': 0,
      'stealingStatus.targetMood': mood,
      'stealingStatus.timeRemaining': duration
    });
    
    this.startStealCountdown();
    
    wx.showToast({
      title: `${this.data.selectedCharacter.name}开始偷取${mood}`,
      icon: 'success'
    });
  },

  // 更新角色经验
  updateCharacterExperience(characterId, exp) {
    try {
      const characters = this.data.characters.map(char => {
        if (char.id === characterId) {
          const newExp = char.experience + exp;
          const newLevel = Math.floor(newExp / char.maxExperience) + 1;
          const levelUp = newLevel > char.level;
          
          return {
            ...char,
            experience: newExp % char.maxExperience,
            level: Math.max(char.level, newLevel),
            lastActive: this.formatTime(new Date())
          };
        }
        return char;
      });
      
      this.setData({ characters });
      
      // 保存到本地存储
      wx.setStorageSync('thief_characters', characters);
      
      // 角色升级处理
      const updatedChar = characters.find(c => c.id === characterId);
      if (updatedChar && updatedChar.level > this.data.selectedCharacter.level) {
        this.showLevelUpAnimation(updatedChar);
      }
      
      // 检查角色解锁条件
      this.checkCharacterUnlockConditions();
    } catch (err) {
      console.error('更新角色经验失败', err);
      wx.showToast({
        title: '更新经验失败',
        icon: 'none'
      });
    }
  },
  
  // 检查角色解锁条件
  checkCharacterUnlockConditions() {
    const characters = this.data.characters.map(char => {
      if (!char.unlocked) {
        // 这里可以根据不同角色的解锁条件添加更多逻辑
        if (char.id === 'happy_dog' && this.data.todayStats.totalSteals >= 10) {
          return { ...char, unlocked: true };
        } else if (char.id === 'gentle_rabbit' && this.data.todayStats.moodFragments >= 50) {
          return { ...char, unlocked: true };
        } else if (char.id === 'magic_fox' && this.data.todayStats.moodFragments >= 100) {
          return { ...char, unlocked: true };
        }
      }
      return char;
    });
    
    if (characters.some((char, i) => !this.data.characters[i].unlocked && char.unlocked)) {
      this.setData({ characters });
      wx.showToast({
        title: '新角色已解锁！',
        icon: 'success'
      });
    }
  },
  
  // 格式化时间显示
  formatTime(date) {
    const hours = date.getHours();
    const minutes = date.getMinutes();
    return `${hours}:${minutes.toString().padStart(2, '0')}`;
  },
  
  // 显示升级动画
  showLevelUpAnimation(character) {
    wx.showToast({
      title: `${character.name}升级啦！Lv.${character.level}`,
      icon: 'success',
      duration: 2000
    });
  },

  // 刷新数据
  refreshData() {
    this.loadCharacterData();
    this.checkActiveSteal();
    this.updateTodayStats();
    this.loadUserData();
  },

  loadUserData() {
    // 模拟加载用户数据
    this.setData({
      userInfo: {
        avatarUrl: '/images/user-avatar.jpg',
        nickName: '用户'
      },
      partnerInfo: {
        avatarUrl: '/images/partner-avatar.jpg',
        nickName: '伴侣'
      }
    });
  },
  
  // 更新今日统计数据
  updateTodayStats() {
    // 这里应该从本地存储或服务器获取最新数据
    // 模拟数据更新
    const newStats = {...this.data.todayStats};

    // 重置统计数据（如果需要）
    // newStats.totalSteals = 0;
    // newStats.successfulSteals = 0;
    // newStats.moodFragments = 0;
    // newStats.experienceGained = 0;

    this.setData({todayStats: newStats});
  },

  // 导航到偷取控制台
  onNavigateToConsole() {
    wx.navigateTo({
      url: '/pages/thief/console/index'
    });
  },

  // 导航到追回游戏
  onNavigateToGame() {
    wx.navigateTo({
      url: '/pages/thief/game/index'
    });
  },
  
  // 查看结果
  viewResults() {
    wx.navigateTo({
      url: '/pages/thief/result/index'
    });
  },

  // 分享角色
  onShareCharacter() {
    if (!this.data.selectedCharacter) {
      wx.showToast({
        title: '请先选择角色',
        icon: 'none'
      });
      return;
    }
    
    return {
      title: `我的心情小偷：${this.data.selectedCharacter.name}`,
      path: '/pages/thief/select/index',
      imageUrl: '/images/share-character.png'
    };
  }
});